package edu.sias.controller;

import edu.sias.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(urlPatterns = "/user/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1 设定编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 2 获取用户输入的账号以及密码
        String username = request.getParameter("username");
        String psw = request.getParameter("psw");

        //3 查询数据库，看有无此账号和密码
        UserService userService = new UserService();
        boolean result = userService.loginUser(username, psw);
        //判断下登录结果
        if (result){
            //如果登录成功，设置成功状态
            HttpSession session = request.getSession();
            session.setAttribute("status","success");
            session.setAttribute("name",username);
            //默认跳转到文章信息列表页
            response.sendRedirect("/search");
        }else{
            //登录失败 返回登录页面，同时告诉用户错误
            request.setAttribute("error","账号或密码错误");
            request.getRequestDispatcher("/login.jsp")
                    .forward(request,response);
        }





    }


}
